#include "TcpReceiver.h"

TcpReceiver::TcpReceiver()
{
}

TcpReceiver::~TcpReceiver()
{
	if (_thread != NULL)
		delete _thread;
}

bool TcpReceiver::Initialize(int socketDescriptor)
{
	_thread = new QThread;
	if (_thread != NULL)
	{
		setSocketDescriptor(socketDescriptor);
		connect(this, SIGNAL(readyRead()), this, SLOT(ReadStream()));
		connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnSocketError(QAbstractSocket::SocketError)));
		connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(SocketState(QAbstractSocket::SocketState)));
		connect(this, SIGNAL(disconnected()), this, SLOT(OnDisconnected()));
		_addr = peerAddress();
		moveToThread(_thread);

		OnInitialization();
		_thread->start();
		return true;
	}
	else
		return false;
}

void TcpReceiver::OnInitialization()
{

}

void TcpReceiver::OnReadStream(const char */*s*/, int /*len*/)
{

}

void TcpReceiver::OnSocketError(QAbstractSocket::SocketError /*err*/)
{
}

void TcpReceiver::SocketState(QAbstractSocket::SocketState /*state*/)
{
}

void TcpReceiver::ReadStream()
{
	bool stop = false;
	int rbyte = 0;
	char buf[BUF_SIZE];
	while (!stop && bytesAvailable())
	{
		rbyte = read(buf, BUF_SIZE);
		if (rbyte != -1)
			OnReadStream(buf, rbyte);
		else
			stop = true;
	}
}

void TcpReceiver::OnDisconnected()
{

}
